#! /usr/bin/python
# -*- coding: utf-8 -*-

import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import conf
import utils
import counters
import aimg

class MainPage(webapp.RequestHandler):
    def post(self):
        cookieDict = utils.getXnCookieDict(self.request.cookies)
        isLoggedIn = utils.validateXnCookies(cookieDict, conf.app_secret)
        errMsg = ''
        newImageId = 0
        if not isLoggedIn:
            errMsg = '你已退出登录或超时，请先登录再上传图片'
        if not errMsg:
            #Save uploaded image to datastore
            uploadImg = self.request.get('upload')
            imgtype = self.request.get('imgtype')
            if not uploadImg or not imgtype:
                errMsg = '缺少上传图片参数'
            else:
                counter = counters.AtomicCounter('image')
                newImageId = counter.AtomicInc()
                imgModel = aimg.UploadImage()
                imgModel.imgid = newImageId
                imgModel.contentType = conf.imageSupportContentTypes.get(imgtype)
                imgModel.imgdata = db.Blob(uploadImg)
                imgModel.put()
        templateValues = {
            'staticUrl': conf.staticUrl,
            'jsVersion': conf.jsVersion,
            'cssVersion': conf.cssVersion,
            'siteUrl': conf.siteUrl,
            'errMsg': errMsg,
            'imgId': newImageId
        }
        path = os.path.join(os.path.dirname(__file__), 'pages/imgupload.html')
        self.response.out.write(template.render(path, templateValues))


application = webapp.WSGIApplication(
                                     [('/imgupload', MainPage)],
                                     debug=True)
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
